<?php
declare(strict_types=1);

namespace App\AdminApi\Modular\User\Service;

use App\Common\Enums\StatusEnums;
use App\Common\Modular\User\Model\LevelModel;
use App\Common\Modular\User\Serve\LevelServe;
use Core\Constants\Database;
use Core\Package\ElementPlus\FormCreate\Form;
use Core\Package\ElementPlus\FormCreate\FormItem;
use Zms\Exception\AppException;

class LevelService extends LevelServe
{

    /**
     * 用户标签表单
     * @param mixed|null $id
     * @return Form
     * @throws AppException
     */
    public function levelForm(mixed $id = null): Form
    {
        $values = [];
        if ($id) {
            /**
             * @var LevelModel $level
             */
            $level = $this->search(['id' => $id])->first();
            if (!$level) {
                throw new AppException('编辑失败,等级已失效');
            }
            $rule[] = FormItem::Hidden('id', $level->id);
            $values = [
                'name' => $level->name, 'desc' => $level->desc, 'sort' => $level->sort, 'status' => (string)$level->status
            ];
        }
        $rule[] = FormItem::Input('name', '等级名称')->clearable(true)->maxlength(20)->required('请输入等级名称');
        $rule[] = FormItem::Textarea('desc', '说明/备注')->clearable(true)->maxlength(50);
        $rule[] = FormItem::Number('sort', '排序')->placeholder('序号越大越靠前')->min(Database::INT_MIN)->max(Database::INT_MAX)->clearable(true);
        $rule[] = FormItem::Select('status', '状态', 1)->options(StatusEnums::Datas());
        return Form::create($id ? '编辑会员等级' : '添加会员等级')
            ->setRules($rule)
            ->setValues($values)
            ->setOptionFormInline(true);
    }
}